package com.justgame.project.service.online.service;

import com.justgame.project.base.utils.OrderUtil;
import com.justgame.project.cloud.common.enums.TimeEnum;
import com.justgame.project.cloud.common.exception.Exc;
import com.justgame.project.cloud.common.util.IdUtils;
import com.justgame.project.cloud.common.util.ShiroUtils;
import com.justgame.project.service.api.dto.OnlineVipDTO;
import com.justgame.project.service.api.entity.SysUserInfo;
import com.justgame.project.service.api.feign.ISysDictClient;
import com.justgame.project.service.api.feign.ISysUserInfoClient;
import com.justgame.project.service.api.vo.SysDictVO;
import com.justgame.project.service.online.mapper.OnlineVipMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class OnlineVipService {
    private final ISysUserInfoClient userInfoClient;
    private final ISysDictClient sysDictClient;
    private final OnlineVipMapper vipMapper;
    /**
     * 通过id查询用户是否是vip
     * @param id
     * @return
     * @throws Exc
     */
    public Boolean isVip(Object id) throws Exc {
        if (id instanceof String){
            return vipMapper.isVipByUserId((String) id);
        }else if (id instanceof Long){
            return vipMapper.isVipByOnlineId((Long) id);
        }else{
            throw new Exc("未知的ID类型！");
        }
    }

    public Map<String, Map<String,Object>> getVipServerShow(){
        Map<String, Map<String,Object>> result = new LinkedHashMap<>();
        List<SysDictVO> dicts = sysDictClient.getDictByCode("vip_time_&_cost");
        boolean isFirst = vipMapper.isNeverVipByUserId(ShiroUtils.getUserId());
        for (SysDictVO d : dicts) {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("serverId",d.getId());
            item.put("time", d.getDictKey());
            /* 新用户首单8折 */
            if (isFirst){
                item.put("originalCost", d.getDictValue());
                item.put("cost", BigDecimal.valueOf(Double.parseDouble(d.getDictValue()) * 0.8).setScale(2, RoundingMode.HALF_UP).doubleValue());
                item.put("note", "首单享8折优惠");
            }else{
                item.put("cost", d.getDictValue());
            }
            result.put(d.getRemark(), item);
        }
        return result;
    }

    public Boolean handleVipService(OnlineVipDTO dto,HttpServletRequest request){
        if (StringUtils.isBlank(dto.getVipServerDictId())){
            throw new Exc("请先选择要开通VIP会员的类型！");
        }
        SysDictVO vipServer = sysDictClient.getDictById(dto.getVipServerDictId());
        if (vipServer == null || !"vip_time_&_cost".equals(vipServer.getCode())){
            throw new Exc("该VIP会员服务类型不存在！");
        }
        SysDictVO payMethod = sysDictClient.getDictById(dto.getPayMethodId());
        if (payMethod == null || !"pay_method".equals(payMethod.getCode())){
            throw new Exc("该支付方式不存在！");
        }
        /* 查询用户信息 */
        String userId = ShiroUtils.getUserId();
        if (StringUtils.isBlank(userId)){
            throw new Exc("请先登录后再试！");
        }
        SysUserInfo user = userInfoClient.getUserInfoById(userId);
        if (user == null){
            throw new Exc("用户信息不存在！");
        }
        /*
         *  【 站内订单 】
         */
        String orderNo = OrderUtil.buildVipOrderCode();
        Date now = new Date();
        OnlineVipDTO vip = new OnlineVipDTO();
        vip.setOnlineId(user.getOnlineId());
        vip.setUserId(user.getId());
        /* 查询最晚过期日期 */
        Date finalExpireDate = vipMapper.selectFinalExpireDate(vip);
        vip.setCreateDate(now);
        /* 判断此用户是否vip已过期或者不是vip */
        if (finalExpireDate == null || finalExpireDate.before(now)){
            /* 新VIP */
            vip.setEffectDate(now);
            vip.setExpireDate(TimeEnum.DAY.calculateEndDate(now,Integer.parseInt(vipServer.getDictKey())));
        }else{
            /* 续费 */
            vip.setEffectDate(finalExpireDate);
            vip.setExpireDate(TimeEnum.DAY.calculateEndDate(finalExpireDate,Integer.parseInt(vipServer.getDictKey())));
        }
        vip.setPayMoney(vipServer.getDictValue());
        vip.setPayType(Integer.parseInt(payMethod.getDictValue()));
        vip.setOrderId(orderNo);
        vip.setPaySuccess(1);
        vip.setId(IdUtils.create());
        /* 判断是否是新用户，新用户首次办理8折优惠 */
        boolean isFirst = vipMapper.isNeverVipByUserId(ShiroUtils.getUserId());
        /*
         * 【 支付接口订单 】
         */
        //OrderUtil.PayRequestModel model = new OrderUtil.PayRequestModel();
        //model.setPaytype(payMethod.getDictKey());
        //model.setThirduid(userId);
        //if (isFirst){
        //    model.setPrice(BigDecimal.valueOf(Float.parseFloat(vipServer.getDictValue()) * 0.8).setScale(2, RoundingMode.HALF_UP).floatValue());
        //    model.setName("VIP会员服务（新用户首单8折优惠）");
        //}else{
        //    model.setPrice(Float.parseFloat(vipServer.getDictValue()));
        //    model.setName("VIP会员服务");
        //}
        //OrderUtil.PayResponseModel payResponse = HttpUtil.getPay(model);

        /* 生成vip信息 */
        return vipMapper.insert(vip) > 0;
    }



}
